package gorm

import (
	"database/sql/driver"
	"encoding/json"
	"fmt"
	"gorm.io/gorm"
	"time"
)

const timeFormat = "2006-01-02 15:04:05"

type DeletedAt gorm.DeletedAt

type Time struct {
	time.Time
}

func (r *Time) UnmarshalJSON(b []byte) error {
	var s string
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}

	t, err := time.Parse(timeFormat, s)
	if err != nil {
		return err
	}
	r.Time = t

	return nil
}
func (r *Time) MarshalJSON() ([]byte, error) {
	return json.Marshal(r.Time.Format(timeFormat))
}

func (r *Time) Scan(value interface{}) error {
	if value == nil {
		*r = Time{Time: time.Time{}}
		return nil
	}
	t, ok := value.(time.Time)
	if !ok {
		return fmt.Errorf("cannot convert %v to time.Time", value)
	}
	*r = Time{Time: t}
	return nil
}
func (r *Time) Value() (driver.Value, error) {
	if r == nil || r.Time.IsZero() {
		return time.Now().Format(timeFormat), nil
	}
	return r.Time.Format(timeFormat), nil
}
func (r *Time) String() string {
	return r.Time.Format(timeFormat)
}
